<template>
  <div class="chapter-list">
    <div class="page-header">
      <h1>章节选择</h1>
    </div>
    
    <div class="chapter-grid">
      <div v-if="loading" class="loading-container">
        <a-spin size="large" />
        <p>正在加载章节信息...</p>
      </div>
      
      <div
        v-else
        v-for="chapter in chapters"
        :key="chapter.nodenum"
        class="chapter-card"
        :class="{
          'available': chapter.nodenum <= currentAllowNode,
          'locked': chapter.nodenum > currentAllowNode,
          'completed': chapter.nodenum < currentAllowNode
        }"
        @click="handleChapterClick(chapter)"
      >
        <div class="chapter-icon">
          <IconCheckCircleFill v-if="chapter.nodenum < currentAllowNode" class="completed-icon" />
          <IconLock v-else-if="chapter.nodenum > currentAllowNode" class="locked-icon" />
          <IconPlayArrowFill v-else class="play-icon" />
        </div>
        
        <div class="chapter-content">
          <h3>{{ chapter.title }}</h3>
          <p>{{ chapter.description || '心理思维训练章节' }}</p>
          <div class="chapter-status">
            <a-tag v-if="chapter.nodenum < currentAllowNode" color="green">已完成</a-tag>
            <a-tag v-else-if="chapter.nodenum === currentAllowNode" color="orange">当前章节</a-tag>
            <a-tag v-else color="gray">未解锁</a-tag>
          </div>
        </div>
        
        <div class="chapter-arrow">
          <IconRight />
        </div>
      </div>
    </div>
    
    <div class="progress-section">
      <h3>学习进度</h3>

      <p class="progress-text">
        已完成 {{ currentAllowNode }} / {{ totalChapters }} 个章节
      </p>
    </div>
    
    <!-- 问卷调查提示模态框 -->
    <a-modal
      v-model:visible="surveyModalVisible"
      :footer="false"
      :closable="true"
      @cancel="closeSurveyModal"
      width="350px"
    >
      <template #title>
        <IconTrophy style="margin-right: 8px; color: #ffb400;" />
        恭喜完成本章节！
      </template>
      <div class="survey-content">
        <div class="survey-icon">
          <IconCheckCircleFill style="font-size: 48px; color: #00b42a;" />
        </div>
        <h3>感谢您完成本章节的训练！</h3>
        <p class="survey-description">
          为了更好地了解您的训练体验和效果，我们诚邀您参与一项青少年心理思维训练问卷调查。
        </p>
        <p class="survey-info">
          问卷填写约需 <strong>5分钟</strong>，您的所有信息将严格保密，仅用于科学研究。
        </p>
        <div class="survey-actions">
          <a-button type="primary" size="large" @click="openSurveyLink" class="survey-btn">
            <template #icon>
              <IconLink />
            </template>
            参与问卷调查
          </a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import { 
  IconCheckCircleFill, 
  IconLock, 
  IconPlayArrowFill, 
  IconRight,
  IconLink,
  IconTrophy
} from '@arco-design/web-vue/es/icon'
import { useUserStore } from '../../stores/user'
import { chapterApi } from '../../api'

const router = useRouter()
const userStore = useUserStore()

const chapters = ref<any[]>([])
const loading = ref(false)
const surveyModalVisible = ref(false)
const completedChapter = ref(0) // 记录完成的章节编号

  // 不同章节的问卷链接
  const surveyLinks: Record<number, string> = {
    1: 'https://v.wjx.cn/vm/mBVyCZx.aspx', // E1 章节问卷
    2: 'https://v.wjx.cn/vm/h5HOXz5.aspx', // E2 章节问卷
    3: 'https://v.wjx.cn/vm/mHG4yCz.aspx', // E3 章节问卷
    4: 'https://v.wjx.cn/vm/rAiwLGz.aspx', // E4 章节问卷
    5: 'https://v.wjx.cn/vm/OPRzzZi.aspx', // E5 章节问卷
    6: 'https://v.wjx.cn/vm/eZFtCz6.aspx', // E6 章节问卷
  }

const currentAllowNode = computed(() => {
  return userStore.currentAllowNode
})

const totalChapters = computed(() => {
  return chapters.value.length
})

const handleChapterClick = (chapter: any) => {
  if (chapter.nodenum > currentAllowNode.value) {
    Message.warning('请先完成前面的章节')
    return
  }
  
  if (chapter.nodenum < currentAllowNode.value) {
    Message.info('您已完成此章节，可以重新体验')
  }
  
  router.push(`/user/question/${chapter.nodenum}`)
}

const loadChapters = async () => {
  loading.value = true
  try {
    const response = await chapterApi.getChapters()
    if (response.success) {
      chapters.value = response.data
    } else {
      Message.error(response.message || '获取章节信息失败')
    }
  } catch (error) {
    console.error('获取章节信息失败:', error)
    Message.error('网络错误，请重试')
  } finally {
    loading.value = false
  }
}

// 打开问卷调查链接
const openSurveyLink = () => {
  const surveyUrl = surveyLinks[completedChapter.value] || surveyLinks[1]
  console.log('🔗 打开问卷链接:', { chapter: completedChapter.value, url: surveyUrl })
  window.open(surveyUrl, '_blank')
  closeSurveyModal()
}

// 关闭问卷调查模态框
const closeSurveyModal = () => {
  surveyModalVisible.value = false
  // 清除标记
  sessionStorage.removeItem('chapterCompleted')
  sessionStorage.removeItem('completedChapterNum')
}

// 检查是否刚完成章节
const checkChapterCompletion = () => {
  const completed = sessionStorage.getItem('chapterCompleted')
  const chapterNum = sessionStorage.getItem('completedChapterNum')
  
  console.log('🔍 检查章节完成状态:', { completed, chapterNum })
  
  if (completed === 'true' && chapterNum) {
    completedChapter.value = parseInt(chapterNum)
    console.log('✅ 完成的章节:', completedChapter.value)
    
    // 显示问卷（1-6章节，E0导入单元不显示问卷）
    if (completedChapter.value >= 1 && completedChapter.value <= 6) {
      console.log('📋 准备显示问卷，章节:', completedChapter.value)
      // 延迟显示，让用户先看到章节列表
      setTimeout(() => {
        console.log('📋 显示问卷模态框')
        surveyModalVisible.value = true
      }, 500)
    } else {
      console.log('⚠️ 章节不在1-6范围内，不显示问卷')
      // 清除标记
      sessionStorage.removeItem('chapterCompleted')
      sessionStorage.removeItem('completedChapterNum')
    }
  } else {
    console.log('❌ 没有完成章节标记')
  }
}

onMounted(() => {
  loadChapters()
  checkChapterCompletion()
})
</script>

<style scoped>
.chapter-list {
  max-width: 800px;
  margin:20px;
}

.page-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-header h1 {
  color: #1d2129;
  margin-bottom: 8px;
  font-size: 28px;
  font-weight: 600;
}

.page-header p {
  color: #86909c;
  font-size: 16px;
  margin: 0;
}

.chapter-grid {
  display: flex;
  flex-direction: column;
  gap: 16px;
  margin-bottom: 40px;
}

.chapter-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 2px solid transparent;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chapter-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.chapter-card.available {
  border-color: #165dff;
}

.chapter-card.available:hover {
  border-color: #0e42d2;
}

.chapter-card.completed {
  background: #f2f8f2;
  border-color: #00b42a;
}

.chapter-card.locked {
  background: #f7f8fa;
  cursor: not-allowed;
  opacity: 0.6;
}

.chapter-card.locked:hover {
  transform: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chapter-icon {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.completed-icon {
  color: #00b42a;
}

.locked-icon {
  color: #86909c;
}

.play-icon {
  color: #165dff;
}

.chapter-content {
  flex: 1;
}

.chapter-content h3 {
  color: #1d2129;
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
}

.chapter-content p {
  color: #4e5969;
  margin: 0 0 12px 0;
  font-size: 14px;
}

.chapter-status {
  display: flex;
  gap: 8px;
}

.chapter-arrow {
  color: #86909c;
  font-size: 16px;
}

.progress-section {
  background: white;
  border-radius: 12px;
  padding: 24px;
  text-align: center;
}

.progress-section h3 {
  color: #1d2129;
  margin: 0 0 16px 0;
  font-size: 18px;
  font-weight: 600;
}

.progress-text {
  color: #4e5969;
  margin: 12px 0 0 0;
  font-size: 14px;
}

.loading-container {
  text-align: center;
  padding: 80px 20px;
  color: #4e5969;
}

.loading-container p {
  margin-top: 16px;
  font-size: 14px;
}

/* 问卷调查模态框样式 */
.survey-content {
  text-align: center;
  padding: 20px 10px;
}

.survey-icon {
  margin-bottom: 20px;
  animation: bounce 1s ease;
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10px);
  }
  60% {
    transform: translateY(-5px);
  }
}

.survey-content h3 {
  color: #1d2129;
  font-size: 20px;
  font-weight: 600;
  margin: 0 0 16px 0;
}

.survey-description {
  color: #4e5969;
  font-size: 15px;
  line-height: 1.6;
  margin: 0 0 12px 0;
}

.survey-info {
  color: #86909c;
  font-size: 14px;
  line-height: 1.6;
  margin: 0 0 24px 0;
}

.survey-info strong {
  color: #165dff;
  font-weight: 600;
}

.survey-actions {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 0;
}

.survey-btn {
  width: 100%;
  height: 44px;
  font-size: 16px;
  font-weight: 500;
}

/* 移动端响应式 */
@media (max-width: 480px) {
  .survey-content {
    padding: 10px 5px;
  }
  
  .survey-content h3 {
    font-size: 18px;
  }
  
  .survey-description,
  .survey-info {
    font-size: 14px;
  }
}
</style>
